﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using EvidenceManagement.Data;

namespace EvidenceManagement.Logic.Security
{
    public sealed class CryptographyManager:ICrytographyManager
    {
        const string HashingNameKey = "AlgorithmHashName";

        readonly EvidenceManagementDataAccessor dataAccessor;

        public CryptographyManager()
        {

        }

        public CryptographyManager(EvidenceManagementDataAccessor dataAccessor)
        {
            this.dataAccessor = dataAccessor;            
        }

        private string GetHashingName()
        {
            return dataAccessor.GetConfigValue(HashingNameKey);
        }



        #region ICrytographyManager Members

        public HashAlgorithm GetHashAlgorithm()
        {
            string hashName = GetHashingName();
            HashAlgorithm algorithm = HashAlgorithm.Create(hashName);

            if (algorithm == null)
                throw new CryptographicException("Error creating hashing algorithm for given configuration name");
            else
                return algorithm;
        }

        public byte[] GenerateSaltBytes(int byteArrayLength)
        {
            if(byteArrayLength<1)
                throw new ArgumentException("Lenght cannot be less than or equal to zero (0).", "byteArrayLength");

            byte[] saltBytes = new byte[byteArrayLength];
            RNGCryptoServiceProvider.Create().GetNonZeroBytes(saltBytes);

            return saltBytes;
        }

        public string GenerateHashString(HashAlgorithm algorithm, byte[] data)
        {
            if (data == null)
                throw new ArgumentNullException("data");
            
            if (algorithm == null)
                throw new ArgumentNullException("algorithm");

            byte[] hashedBytes = algorithm.ComputeHash(data);
            return Convert.ToBase64String(hashedBytes);
        }

        #endregion
    }
}
